
package com.xiashitech.apiservice.api;

import java.util.*;
import static com.xiashitech.apiservice.Constants.ErrorCode.*;

import com.google.common.collect.Maps;
import com.xiashitech.apiservice.dao.model.DataWaterMarkConfig;
import com.xiashitech.apiservice.dto.Pager;
import com.xiashitech.apiservice.dto.Result;
import com.xiashitech.apiservice.service.IDataWaterMarkConfigService;
import lombok.RequiredArgsConstructor;
import lombok.var;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.*;
import org.apache.commons.lang3.*;

@Controller
@RequestMapping("v1")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class DataWaterMarkConfigController {

    private static final Log log = LogFactory.get();
    private final IDataWaterMarkConfigService dataWaterMarkConfigService;

    @RequestMapping(value = "server/createDataWaterMarkConfig", method = RequestMethod.POST)
    @ResponseBody
    public Result<Void> createDataWaterMarkConfig(@RequestBody DataWaterMarkConfig data) {
        Result<Void> result = isValid(data);
        if (Integer.parseInt(RESULT_4014.getCode()) == result.getStatus()) {
            return result;
        }
        Date date = new Date();
        data.setCreateDate(date);
        data.setUpdateDate(date);
        try {
            int affectedRows = dataWaterMarkConfigService.insertDataWaterMarkConfig(data);
            if (affectedRows == 0)
                return Result.failure(RESULT_5006);
            result = Result.success();
        } catch (Exception e) {
            log.info("Error processing request:{}", e.getMessage());
            result = Result.failure();
        }
        return result;
    }

    @RequestMapping(value = "server/updateDataWaterMarkConfig", method = RequestMethod.POST)
    @ResponseBody
    public Result<Void> updateDataWaterMarkConfig(@RequestBody DataWaterMarkConfig data) {
        Result<Void> result = isValid(data);
        if (Integer.parseInt(RESULT_4014.getCode()) == result.getStatus()) {
            return result;
        }
        data.setUpdateDate(new Date());
        try {
            int affectedRows = dataWaterMarkConfigService.updateDataWaterMarkConfig(data);
            if (affectedRows == 0)
                return Result.failure(RESULT_5006);
            result = Result.success();
        } catch (Exception e) {
            log.info(e);
            result = Result.failure();
        }
        return result;
    }

    @RequestMapping(value = "server/deleteDataWaterMarkConfig", method = RequestMethod.POST)
    @ResponseBody
    public Result<Void> deleteDataWaterMarkConfig(@RequestBody List<Long> ids) {
        Result<Void> result = Result.failure();
        try {
            int affectedRows = dataWaterMarkConfigService.deleteDataWaterMarkConfig(ids);
            if (affectedRows == 0)
                return Result.failure(RESULT_5006);
            result = Result.success();
        } catch (Exception e) {
            log.info("Error processing request:{}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "agent/searchDataWaterMarkConfig", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<DataWaterMarkConfig>> searchDataWaterMarkConfigs(@RequestBody DataWaterMarkConfig data) {
        Result<List<DataWaterMarkConfig>> result = isEmpty(data);
        if (Integer.parseInt(RESULT_4014.getCode()) == result.getStatus()) {
            return result;
        }
        try {
            result = Result.success(dataWaterMarkConfigService.getDataWaterMarkConfigList(data));
        } catch (Exception e) {
            log.info("Error processing request:{}", e.getMessage());
            result = Result.failure();
        }
        return result;
    }

    @RequestMapping(value = "server/searchDataWaterMarkConfig/{page}/{size}", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<DataWaterMarkConfig>> searchDataWaterMarkConfigs(@RequestBody JSONObject data,
            @PathVariable int page,
            @PathVariable int size) {
        Result<List<DataWaterMarkConfig>> result = Result.failure();
        try {
            Pager<DataWaterMarkConfig> pager = new Pager<>();
            pager.setOffset((page - 1) * size);
            pager.setLimit(size);
            var obj = data.getJSONObject("obj");
            if (!JSONUtil.isNull(obj) && !obj.isEmpty()) {
                pager.setRows(JSONUtil.toBean(obj, DataWaterMarkConfig.class));
            }
            var conditions = data.getJSONObject("conditions");
            if (!JSONUtil.isNull(conditions) && !conditions.isEmpty()) {
                pager.setConditions(new HashMap<>(conditions));
            }
            result = Result.success(dataWaterMarkConfigService.getDataWaterMarkConfigListPage(pager));
        } catch (Exception e) {
            log.error("Error processing request:{}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "server/getDataWaterMarkConfigCount", method = RequestMethod.POST)
    @ResponseBody
    public Result<Long> getDataWaterMarkConfigCount(@RequestBody JSONObject data) {
        Result<Long> result = Result.failure();
        try {
            Map<String, Object> parameters = Maps.newHashMap();
            var obj = data.getJSONObject("obj");
            if (!JSONUtil.isNull(obj) && !obj.isEmpty()) {
                parameters = JSONUtil.toBean(obj, Map.class);
            }
            var conditions = data.getJSONObject("conditions");
            if (!JSONUtil.isNull(conditions) && !conditions.isEmpty()) {
                parameters.putAll(new HashMap<>(conditions));
            }
            result = Result.success(dataWaterMarkConfigService.getDataWaterMarkConfigCount(parameters));
        } catch (Exception e) {
            log.info("Error processing request:{}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "server/searchDataWaterMarkConfig/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result<DataWaterMarkConfig> searchDataWaterMarkConfig(@PathVariable Long id) {
        Result<DataWaterMarkConfig> result = Result.failure();
        try {
            result = Result.success(dataWaterMarkConfigService.getDataWaterMarkConfigById(id));
            if (Objects.isNull(result)) {
                result = Result.failure(RESULT_5005);
            }
        } catch (Exception e) {
            log.info("Error processing request:{}", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "agent/watermarkmode/{systemId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<JSONObject> getWaterMarkMode(@PathVariable String systemId){
        return dataWaterMarkConfigService.getWaterMarkMode(systemId);
    }

    private <T> Result<T> isEmpty(DataWaterMarkConfig data) {
        Result<T> result = new Result<>();
        if (Objects.isNull(data)) {
            result = Result.failure(RESULT_4014);
        }
        return result;
    }

    private <T> Result<T> isValid(DataWaterMarkConfig data) {
        Result<T> result = isEmpty(data);
        if (Integer.parseInt(RESULT_4014.getCode()) == result.getStatus()) {
            return result;
        }
        if (StringUtils.isAnyBlank(data.getFlag(), data.getApiPath(), data.getOperator(), data.getAppName())) {
            result.setStatus(Integer.parseInt(RESULT_4014.getCode()));
            result.setMessage(RESULT_4014.getMessage() + "：flag,apiPath,operator,appName");
        }
        if (!data.getFlag().matches("[01]{5}")) {
            result.setStatus(Integer.parseInt(RESULT_4014.getCode()));
            result.setMessage(RESULT_4014.getMessage() + ": flag是由0/1组成的长度为5的标志位");
        }
        if (Objects.isNull(data.getMorethanLine()) || data.getMorethanLine() <= 0) {
            result.setStatus(Integer.parseInt(RESULT_4014.getCode()));
            result.setMessage(RESULT_4014.getMessage() + ": morethanLine必须为大于零的整数");
        }
        if (Objects.nonNull(data.getId()) && data.getId() <= 0) {
            result.setStatus(Integer.parseInt(RESULT_4014.getCode()));
            result.setMessage(RESULT_4014.getMessage() + ":Id必须为大于零的整数");
        }
        return result;
    }
}